package com.example.iread.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.example.iread.R;
import com.example.iread.adapter.BookChapterAdapter;
import com.example.iread.bean.ChapterBean;
import com.example.iread.exception.MyException;
import com.example.iread.http.ChapterApi;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

public class BookChapterFragment extends Fragment {

    private final int bookId;
    private TextView tv_chapter_total, tv_chapter_page;
    private ListView lv_book_chapter;

    private Context context;

    public BookChapterFragment(int bookId) {
        this.bookId = bookId;
    }

    private final int pageSize = 5;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            List<ChapterBean> list = (List) msg.obj;

            Bundle data = msg.getData();
            int total = data.getInt("total");

            tv_chapter_total.setText("Total: " + total);
            lv_book_chapter.setAdapter(new BookChapterAdapter(context, list));
            tv_chapter_page.setOnClickListener(v -> {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Please select page");
                int pageTotal = (int) Math.ceil((double) total / (double) pageSize);
                String[] strings = new String[pageTotal];
                for (int i = 0; i < pageTotal; i++) {
                    strings[i] = String.valueOf(i + 1);
                }
                builder.setItems(strings, (dialogInterface, i) -> getData(i + 1));
                builder.create().show();
            });
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_chapter, container, false);

        context = view.getContext();

        lv_book_chapter = view.findViewById(R.id.lv_book_chapter);
        tv_chapter_total = view.findViewById(R.id.tv_chapter_total);
        tv_chapter_page = view.findViewById(R.id.tv_chapter_page);

        getData(1);

        return view;
    }

    @SuppressLint("SetTextI18n")
    public void getData(int page) {
        ChapterApi.getByBookId(page, pageSize, bookId, res -> {
            Type type = TypeToken.getParameterized(List.class, ChapterBean.class).getType();
            String json = new GsonBuilder().serializeNulls().create().toJson(res.data);
            try {
                JSONObject jsonObject = new JSONObject(json);
                String rows = jsonObject.getJSONArray("rows").toString();
                int total = jsonObject.getInt("total");
                List<ChapterBean> list = new GsonBuilder().serializeNulls().create().fromJson(rows, type);

                Message message = handler.obtainMessage(0, list);
                Bundle bundle = new Bundle();
                bundle.putInt("total", total);
                message.setData(bundle);
                handler.sendMessage(message);
            } catch (JSONException e) {
                throw new MyException(500, e.getMessage());
            }
        });
    }
}